#!/usr/bin/env python3
"""
Test script for the optimized directory tree service
"""

import asyncio
import sys
from pathlib import Path

# Add project root to path
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from app.services.directory_tree_service_optimized import directory_tree_service_optimized
from app.core.config import settings

async def test_optimized_service():
    """Test the optimized directory tree service"""
    print("🧪 Testing optimized directory tree service...")

    # Create database connection
    db_path = project_root / "data" / "uma_insight.db"
    database_url = f"sqlite+aiosqlite:///{db_path}"

    engine = create_async_engine(
        database_url,
        echo=False,
        future=True
    )

    async_session_maker = sessionmaker(engine, class_=AsyncSession)

    async with async_session_maker() as db:
        try:
            # Test 1: Get all directory statistics
            print("\n📊 Test 1: Getting all directory statistics...")
            result = await directory_tree_service_optimized.get_directory_statistics(db, db)

            if result.get("success"):
                print(f"✅ Success! Found {len(result['data'])} directories")
                print(f"   Total metrics: {result['stats']['total_metrics']}")
                print(f"   Analyzed: {result['stats']['total_analyzed']}")
                print(f"   Not analyzed: {result['stats']['total_not_analyzed']}")
            else:
                print(f"❌ Failed: {result}")

            # Test 2: Get specific directory details (accessibility)
            print("\n📁 Test 2: Getting accessibility directory details...")
            result = await directory_tree_service_optimized.get_directory_details(
                db, db, "tools/metrics/histograms/metadata/accessibility", include_metrics=False
            )

            if result.get("success"):
                print(f"✅ Success! Directory: {result['directory']['name']}")
                print(f"   Path: {result['directory']['path']}")
                print(f"   Metrics count: {result['metrics_count']}")
                print(f"   Team: {result['directory']['team_name']}")
            else:
                print(f"❌ Failed: {result}")

            # Test 3: Get specific directory with metrics
            print("\n📄 Test 3: Getting accessibility directory with metrics...")
            result = await directory_tree_service_optimized.get_directory_details(
                db, db, "tools/metrics/histograms/metadata/accessibility", include_metrics=True
            )

            if result.get("success") and result.get("metrics"):
                print(f"✅ Success! Found {len(result['metrics'])} metrics")
                # Show first 3 metrics as examples
                for i, metric in enumerate(result['metrics'][:3]):
                    print(f"   {i+1}. {metric['name']} ({metric['type']})")
                if len(result['metrics']) > 3:
                    print(f"   ... and {len(result['metrics']) - 3} more")
            else:
                print(f"❌ Failed or no metrics found")

        except Exception as e:
            print(f"❌ Test failed: {e}")
            import traceback
            traceback.print_exc()

        finally:
            await engine.dispose()

if __name__ == "__main__":
    asyncio.run(test_optimized_service())